package com.kehutong.house.admin;

import com.kehutong.common.DoveClient;
import com.kehutong.common.ExcelUtil;
import com.kehutong.common.entity.Root;
import com.kehutong.common.enums.CardType;
import com.kehutong.common.enums.HouseType;
import com.kehutong.common.permission.DataPermissionQuery;
import com.kehutong.common.permission.PermissionNameDto;
import com.kehutong.common.urlconfig.FileUrlConfig;
import com.kehutong.common.util.Token;
import com.kehutong.house.dao.ShopDao;
import com.kehutong.house.entity.*;
import com.kehutong.house.enums.*;
import com.kehutong.house.service.BasicService;
import com.kehutong.house.service.HouseService;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFColor;
import org.apache.poi.xssf.usermodel.XSSFFont;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.coraframework.authz.HasPermission;
import org.coraframework.bean.Beans;
import org.coraframework.inject.Inject;
import org.coraframework.json.JSONArray;
import org.coraframework.json.JSONObject;
import org.coraframework.logger.Logger;
import org.coraframework.logger.LoggerFactory;
import org.coraframework.mvc.MvcAction;
import org.coraframework.mvc.http.Bean;
import org.coraframework.mvc.http.ReqMapping;
import org.coraframework.mvc.http.result.Result;
import org.coraframework.orm.Pool;
import org.coraframework.orm.jdbc.JdbcSession;
import org.coraframework.orm.jdbc.Page;
import org.coraframework.orm.jdbc.execute.Condition;
import org.coraframework.orm.jdbc.execute.PageCondition;
import org.coraframework.orm.jdbc.execute.QueryCondition;
import org.coraframework.orm.jdbc.execute.entity.FindArray;
import org.coraframework.orm.jdbc.execute.entity.FindOne;
import org.coraframework.util.EnumUtil;
import org.coraframework.util.Objects;

import java.io.File;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.*;

/**
 * 商铺
 */
@MvcAction
@ReqMapping("/admin/basic/shop")
public class ShopController {

    @Inject
    private JdbcSession jdbcSession;
    @Inject
    private DoveClient doveClient;
    @Inject
    private FileUrlConfig fileUrlConfig;
    @Inject
    private ShopDao shopDao;
    @Inject
    private HouseService houseService;
    @Inject
    private BasicService basicService;

    public final static String[] EXCEL_IMPORT_HEADER = {"项目/小区", "商铺分类", "商铺", "别名", "物业类型", "建筑面积(㎡)", "实用面积(㎡)", "计费面积(㎡)"
            , "销售转态", "收房状态", "装修状态","出租状态", "姓名", "手机号码", "证件号码"};

    static final Logger logger = LoggerFactory.getLogger(ShopController.class);

    private final static String businessType = "1103";

    @HasPermission("basic:shop:view")
    @ReqMapping("/list")
    public Object list(Token token, JSONObject jsonObject) throws Exception {
        PageCondition query = Condition.createPage(false);
//                .authorize("s.departmentNo","s.departmentNos");

		JSONArray employeeNos = jsonObject.getJSONArray("employeeNos");
		if(Objects.nonEmpty(employeeNos)){
            query.markBegin();
			for (Object item: employeeNos) {
                query.like("b.employeeNos",String.valueOf(item)).or();
			}
            query.markEnd().and();
		}

        String search = jsonObject.getString("search");
        if(Objects.nonEmpty(search)){
            query.markBegin();
            query.like("s.viewName", search).or();
            query.like("s.name", search).or();
            query.markEnd();
        }

        String communityName = jsonObject.getString("communityName");
		if(Objects.nonEmpty(communityName)){
            query.like("s.communityName", communityName);
        }

        String shopClassifyNo = jsonObject.getString("shopClassifyNo");
        if(Objects.nonEmpty(shopClassifyNo)){
            query.eq("s.shopClassifyNo", shopClassifyNo);
        }

        String shopClassifyName = jsonObject.getString("shopClassifyName");
        if(Objects.nonEmpty(shopClassifyName)){
            query.like("s.shopClassifyName", shopClassifyName);
        }

        String name = jsonObject.getString("name");
        if(Objects.nonEmpty(name)){
            query.like("s.name", name);
        }

        String communityNo = jsonObject.getString("communityNo");
        if(Objects.nonEmpty(communityNo)){
            query.eq("s.communityNo", communityNo);
        }

        String ownerName = jsonObject.getString("ownerName");
        if(Objects.nonEmpty(ownerName)){
            query.like("s.ownerName", ownerName);
        }

        String ownerMobile = jsonObject.getString("ownerMobile");
        if(Objects.nonEmpty(ownerMobile)){
            query.like("s.ownerMobile", ownerMobile);
        }

        //排除住户已经占用的商铺
        String residentNo=jsonObject.getString("residentNo");
        if(Objects.nonEmpty(residentNo)){
            String type=jsonObject.getString("type");
            List<String> notInShopIds = new ArrayList<>();
            JSONObject residentShopResult = doveClient.post("/crm/resident/service/getResidentHouseList", (http) -> {
                http.addHeader("companyNo", token.getCompanyNo());
                JSONObject body = new JSONObject();
                body.put("residentNo",residentNo);
                body.put("bindType", jsonObject.getJSONArray("bindType"));
                body.put("type",type);
                body.put("pageSize",Short.MAX_VALUE);
                http.setBody(body.toJSONString());
            });
            if (residentShopResult.getIntValue("code") == 200) {
                JSONArray residentShopList = residentShopResult.getJSONObject("data").getJSONArray("list");
                if (Objects.nonEmpty(residentShopList)) {
                    for (int i = 0; i < residentShopList.size(); i++) {
                        JSONObject residentShop = residentShopList.getJSONObject(i);
                        notInShopIds.add(residentShop.getString("houseNo"));
                    }
                }
            }
            if(Objects.nonEmpty(notInShopIds)){
                query.noIn("s.id", notInShopIds);
            }
        }
        query.eq("s.deleted", false)
                .order("s.createTime", "desc")
                .page(jsonObject);


        try{
            PermissionNameDto dto = houseService.getShopsPermissionNameDto();
            houseService.setDataSql(query, dto, jsonObject, null);
            Page<Map<String, Object>> page = shopDao.loadPage(query);

            Set<String> employeeIds = new HashSet<>();
            page.getList().forEach(item -> {
                String strs = String.valueOf(item.get("employeeNos"));
                if(Objects.nonEmpty(strs)){
                    employeeIds.addAll(Arrays.asList(strs.split(",")));
                }
            });

            Map<String, JSONObject> employeeMap = getEmployeeMap(token, new ArrayList<>(employeeIds));
            page.getList().forEach(item -> {
                List<String> employeeNames = new ArrayList<>();
                String strs = String.valueOf(item.get("employeeNos"));
                if(Objects.nonEmpty(strs)){
                    List<String> ids = Arrays.asList(strs.split(","));
                    ids.forEach(id ->{
                        JSONObject employee = employeeMap.get(id);
                        if (Objects.nonNull(employee)) {
                            employeeNames.add(employee.getString("name"));
                        }
                    });
                }
                item.put("employeeNames", employeeNames);
            });

            return page;
        }catch (Exception e){
            logger.debug("page=========", e);
        }

        return new Page<>();
    }

    @HasPermission("basic:shop:view")
    @ReqMapping("/get")
    public Object get(Token token, Shop shop) throws Exception {
        ShopClassify shopClassify = Pool.get(ShopClassify.class, shop.getShopClassifyNo());

        if (Objects.nonNull(shopClassify.getEmployeeNos())) {
            Map<String, JSONObject> employeeMap = getEmployeeMap(token, shopClassify.getEmployeeNos());

            List<String> employeeNames = new ArrayList<>();
            shopClassify.getEmployeeNos().forEach(id -> {
                JSONObject employee = employeeMap.get(id);
                if (Objects.nonNull(employee)) {
                    employeeNames.add(employee.getString("name"));
                }
            });
            shop.setEmployeeNames(employeeNames);
        }
        Community community = Pool.get(Community.class, shop.getCommunityNo());
        shop.setParent_ids(community.getParent_ids());

        return shop;
    }

    @ReqMapping("/setStatus")
    public Object setStatus(Shop entity) {
        entity.setEnable(!entity.isEnable());
        jdbcSession.updateById(entity);

        return Result.success();
    }

    @Bean(newInstance = true, copy = true)
    @HasPermission("basic:shop:edit")
    @ReqMapping("/save")
    public Object save(Token token, Shop shop, JSONObject jsonObject) throws Exception {

        //商铺是否已经存在
        FindOne<Shop> find = jdbcSession.findOne(Shop.class)
                .eq("deleted", false)
                .eq("communityNo", shop.getCommunityNo())
                .eq("shopClassifyName", shop.getShopClassifyName())
                .eq("name", shop.getName());

        Shop item = find.exe(false);

        if (Objects.nonNull(item)) {
            return Result.error(0, "当前商铺分类下已有相同的商铺信息，请修改后重试");
        }

        this.setProperty(shop, jsonObject);

        shop.setCreate_by(token.getUsername());
        shop.setCreateUserId(token.getUuid());
        shop.setCreateDepartment(token.getDepartments());
        shop.setCreateChildDepartment(getChildDepartments(token.getDepartments()));

        jdbcSession.insert(shop);

        basicService.saveOperateRecord(token, shop.getId(), businessType, "1", "");

        return shop;
    }

    @Bean(copy = true, isIgnoreNull = false)
    @HasPermission("basic:shop:edit")
    @ReqMapping("/update")
    public Object update(Token token, Shop shop, JSONObject jsonObject) throws Exception {

        //商铺是否已经存在
        FindOne<Shop> find = jdbcSession.findOne(Shop.class)
                .eq("deleted", false)
                .eq("communityNo", shop.getCommunityNo())
                .eq("shopClassifyName", shop.getShopClassifyName())
                .eq("name", shop.getName())
                .noEq("id", shop.getId());

        Shop item = find.exe(false);

        if (Objects.nonNull(item)) {
            return Result.error(0, "当前商铺分类下已有相同的商铺信息，请修改后重试");
        }

        this.setProperty(shop, jsonObject);

        jdbcSession.updateById(shop);

        basicService.saveOperateRecord(token, shop.getId(), businessType, "2", "");

        return Result.success();
    }

    @ReqMapping("/enums")
    public Object getEnums() {
        Map<String, Object> map = new HashMap<>();
        map.put("propertyTypes", Arrays.asList(PropertyType.values()));
        map.put("salesStatus", Arrays.asList(SalesStatus.values()));
        map.put("harvestStatus", Arrays.asList(HarvestStatus.values()));
        map.put("decoratedStasus", Arrays.asList(DecoratedStasus.values()));
        map.put("resideStasus", Arrays.asList(ResideStasus.values()));
        map.put("rentStasus", Arrays.asList(RentStasus.values()));
        return Result.success(map);
    }

    @HasPermission("basic:shop:edit")
    @ReqMapping("/delete")
    public Object delete(Shop shop) throws Exception {

        JSONArray array = new JSONArray();
        JSONObject json = new JSONObject();
        json.put("id", shop.getOwnerNo());
        json.put("type", "1");
        json.put("houseNo", shop.getId());
        array.add(json);
        if (Objects.nonEmpty(array)) {
            doveClient.post("/crm/resident/service/batchDeleteResidentHouse", (http) -> {
                JSONObject body = new JSONObject();
                body.put("array", array);
                http.setBody(body.toJSONString());
            });
        }
        shop.setDeleted(true);
        jdbcSession.updateById(shop);

        return Result.success();
    }

    @HasPermission("basic:shop:edit")
    @ReqMapping("/deleteAll")
    public Object deleteAll(JSONObject jsonObject) throws Exception {
        List<Shop> list = jdbcSession.findArray(Shop.class)
                .in("id", jsonObject.getJSONArray("ids"))
                .eq("deleted", false)
                .exe();

        JSONArray array = new JSONArray();
        list.forEach(item -> {
            JSONObject json = new JSONObject();
            json.put("id", item.getOwnerNo());
            json.put("type", "1");
            json.put("houseNo", item.getId());
            array.add(json);
        });

        if (Objects.nonEmpty(array)) {
            doveClient.post("/crm/resident/service/batchDeleteResidentHouse", (http) -> {
                JSONObject body = new JSONObject();
                body.put("array", array);
                http.setBody(body.toJSONString());
            });
        }

        list.forEach(item -> {
            item.setDeleted(true);
        });
        jdbcSession.updateById(list);

        return Result.success();
    }

    @HasPermission("basic:shop:view")
    @ReqMapping("/getShopTransfer")
    public Object getShopTransfer(Token token, JSONObject jsonObject) throws Exception {
        JSONArray data = new JSONArray(2);

        Integer level = jsonObject.getInteger("level");
        List<JSONObject> array = new ArrayList<>();
        if (level == 1) {
            FindArray<Community> find = jdbcSession.findArray(Community.class)
                    .eq("deleted", false);

            PermissionNameDto dto = houseService.getCommunityPermissionNameDto();
            DataPermissionQuery.setAllDataSql(find, dto, null);
            List<Community> communities = find.exe(false);

            communities.forEach(community -> {
                array.add(communitie2JSONObject(community));
            });
            JSONObject root = root2JSONObject(token);
            data.add(root);
            data.add(array);
        } else if (level == 2) {
            String communityNo = jsonObject.getString("communityNo");
            FindArray<ShopClassify> find = jdbcSession.findArray(ShopClassify.class)
                    .eq(jsonObject, "communityNo")
                    .eq("deleted", false);

            PermissionNameDto dto = getShopClassifyPermissionNameDto();
            DataPermissionQuery.setAllDataSql(find, dto, null);
            List<ShopClassify> shopClassifys = find.exe(false);

            Community community = Pool.get(Community.class, communityNo);
            JSONObject root = communitie2JSONObject(community);
            shopClassifys.forEach(shopClassify -> {
                array.add(shopClassify2JSONObject(communityNo, shopClassify));
            });

            data.add(root);
            data.add(array);
        } else if (level == 3) {
            String shopClassifyNo = jsonObject.getString("shopClassifyNo");

            List<String> notInShopIds = new ArrayList<>();
            JSONObject residentShopResult = doveClient.post("/crm/resident/service/getResidentHouseList", (http) -> {
                http.addHeader("companyNo", token.getCompanyNo());
                JSONObject body = new JSONObject();
                body.put("buildNo", shopClassifyNo);
                body.put("bindType", jsonObject.getJSONArray("bindType"));
                body.put("type", ResidentType.OWNER.getId());
                body.put("pageSize",Short.MAX_VALUE);
                http.setBody(body.toJSONString());
            });
            if (residentShopResult.getIntValue("code") == 200) {
                JSONArray residentShopList = residentShopResult.getJSONObject("data").getJSONArray("list");
                if (Objects.nonEmpty(residentShopList)) {
                    for (int i = 0; i < residentShopList.size(); i++) {
                        JSONObject residentShop = residentShopList.getJSONObject(i);
                        notInShopIds.add(residentShop.getString("houseNo"));
                    }
                }
            }

            QueryCondition query = Condition.createQuery(false);
            query.eq("s.deleted", false);

            if (Objects.nonEmpty(shopClassifyNo)) {
                query.eq("s.shopClassifyNo", shopClassifyNo);
            }
            if (Objects.nonEmpty(notInShopIds)) {
                query.noIn("s.id", notInShopIds);
            }

            PermissionNameDto dto = houseService.getShopsPermissionNameDto();
            DataPermissionQuery.setAllDataSql(query, dto, null);
            List<Map<String, Object>> shops = shopDao.loadList(query);
            ShopClassify shopClassify = Pool.get(ShopClassify.class, shopClassifyNo);
            JSONObject root = shopClassify2JSONObject(shopClassify.getCommunityNo(), shopClassify);
            shops.forEach(shop -> {
                array.add(shop2JSONObject(shopClassify, shop));
            });

            data.add(root);
            data.add(array);
        }

        return Result.success(data);
    }

    private void setProperty(Shop item, JSONObject jsonObject) throws Exception {
        String salesStatus = jsonObject.getString("salesStatus");
        if (Objects.nonNull(salesStatus)) {
            item.setSalesStatus(EnumUtil.getEnum(SalesStatus.class, salesStatus));
        }

        String harvestStatus = jsonObject.getString("harvestStatus");
        if (Objects.nonNull(harvestStatus)) {
            item.setHarvestStatus(EnumUtil.getEnum(HarvestStatus.class, harvestStatus));
        }

        String decoratedStasus = jsonObject.getString("decoratedStasus");
        if (Objects.nonNull(decoratedStasus)) {
            item.setDecoratedStasus(EnumUtil.getEnum(DecoratedStasus.class, decoratedStasus));
        }

        String resideStasus = jsonObject.getString("resideStasus");
        if (Objects.nonNull(resideStasus)) {
            item.setResideStasus(EnumUtil.getEnum(ResideStasus.class, resideStasus));
        }

        String rentStasus = jsonObject.getString("rentStasus");
        if (Objects.nonNull(rentStasus)) {
            item.setRentStasus(EnumUtil.getEnum(RentStasus.class, rentStasus));
        }

        String propertyType = jsonObject.getString("propertyType");
        if (Objects.nonNull(propertyType)) {
            item.setPropertyType(EnumUtil.getEnum(PropertyType.class, propertyType));
        }

        Community com = Pool.get(Community.class, item.getCommunityNo());
        item.setDepartmentNo(com.getParent_id());
        item.setDepartmentNos(com.getParent_ids());

        // 更新标签信息
        List<String> tags = this.saveOrUpdateTag(item);
        if(Objects.nonEmpty(tags)){
            item.setTags(tags);
        }
    }

    /**
     * 报错或更新用户的业务标签
     * @param shop 商铺信息
     * @throws Exception
     */
    public List<String> saveOrUpdateTag(Shop shop) throws Exception{
        JSONArray tagDatas = new JSONArray();

        PropertyType buildType = shop.getPropertyType();
        if(Objects.nonNull(buildType)){
            JSONObject tagObj = new JSONObject();
            tagObj.put("tagGroupName", "建筑类别");
            tagObj.put("tagName", buildType.getDesc());
            tagDatas.add(tagObj);
        }

        if (Objects.nonEmpty(tagDatas)) {
            JSONObject result=doveClient.post("/admin/business/tag/service/batch/add", (http) -> {
                JSONObject body = new JSONObject();
                body.put("dataList", tagDatas);
                http.setBody(body.toJSONString());
            });

            if (result.getIntValue("code") == 200) {
                JSONArray data = result.getJSONArray("data");
                if(Objects.nonEmpty(data)){
                    List<String> tagIds = new ArrayList<>();
                    List<JSONObject> tags = JSONObject.parseArray(data.toJSONString(), JSONObject.class);
                    tags.forEach(tag -> {
                        tagIds.add(tag.getString("id"));
                    });
                    return tagIds;
                }
            }
        }
        return null;
    }

    private void setProperty(Shop item, Map<String,Object> map) {
        Object salesStatus = map.get("salesStatus");
        if (Objects.nonNull(salesStatus)) {
            item.setSalesStatus(EnumUtil.getEnum(SalesStatus.class, String.valueOf(salesStatus)));
        }

        Object harvestStatus = map.get("harvestStatus");
        if (Objects.nonNull(harvestStatus)) {
            item.setHarvestStatus(EnumUtil.getEnum(HarvestStatus.class, String.valueOf(harvestStatus)));
        }

        Object decoratedStasus = map.get("decoratedStasus");
        if (Objects.nonNull(decoratedStasus)) {
            item.setDecoratedStasus(EnumUtil.getEnum(DecoratedStasus.class, String.valueOf(decoratedStasus)));
        }

        Object resideStasus = map.get("resideStasus");
        if (Objects.nonNull(resideStasus)) {
            item.setResideStasus(EnumUtil.getEnum(ResideStasus.class, String.valueOf(resideStasus)));
        }

        Object rentStasus = map.get("rentStasus");
        if (Objects.nonNull(rentStasus)) {
            item.setRentStasus(EnumUtil.getEnum(RentStasus.class, String.valueOf(rentStasus)));
        }

        Object propertyType = map.get("propertyType");
        if (Objects.nonNull(propertyType)) {
            item.setPropertyType(EnumUtil.getEnum(PropertyType.class, String.valueOf(propertyType)));
        }
    }

    private JSONObject communitie2JSONObject(Community community) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("id", community.getId());
        jsonObject.put("pid", community.getParent_ids());
        jsonObject.put("label", community.getName());
        jsonObject.put("level", 2);
        return jsonObject;
    }

    private JSONObject shopClassify2JSONObject(String communityId, ShopClassify shopClassify) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("id", shopClassify.getId());
        jsonObject.put("pid", communityId);
        jsonObject.put("label", shopClassify.getName());
        jsonObject.put("level", 3);
        return jsonObject;
    }

    private JSONObject shop2JSONObject(ShopClassify shopClassify, Map<String, Object> shop) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("id", shop.get("id"));
        jsonObject.put("pid", shopClassify.getId());
        StringBuffer buf = new StringBuffer();
        buf.append(shopClassify.getCommunityName()).append(">").append(shopClassify.getName()).append(">").append(shop.get("name"));
        jsonObject.put("build", buf.toString());
        jsonObject.put("label",shop.get("name"));
        jsonObject.put("user", true);
        jsonObject.put("level", 4);
        return jsonObject;
    }

    private JSONObject root2JSONObject(Token token) throws Exception{
        JSONObject resultDepartment = doveClient.post("/basic/department/service/get", (http) -> {
            http.addHeader("companyNo", token.getCompanyNo());
            http.addParam("id", Root.ROOT_ID);
        });
        JSONObject department = resultDepartment.getJSONObject("data");
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("id", department.getString("id"));
        jsonObject.put("label",department.getString("name"));
        jsonObject.put("level", 1);
        return jsonObject;
    }

    public Map<String, JSONObject> getEmployeeMap(Token token, List<String> employeeIds) throws Exception {
        JSONObject result = doveClient.post("/basic/employee/service/list", http -> {
            http.addHeader("companyNo", token.getCompanyNo());

            JSONObject body = new JSONObject();
            body.put("id", employeeIds);
            body.put("pageNo", 1);
            body.put("pageSize", 1000000);
            http.setBody(body.toString());
        });

        JSONArray data = result.getJSONObject("data").getJSONArray("list");

        if (Objects.isNull(data)) {
            return null;
        }

        Map<String, JSONObject> employeeMap = new HashMap<>();
        data.forEach(item -> {
            JSONObject obj = (JSONObject) item;
            employeeMap.put(obj.getString("id"), obj);
        });

        return employeeMap;
    }

    @HasPermission("basic:shop:view")
    @ReqMapping("/export")
    public Object export(JSONObject jsonObject,Token token) throws Exception {
        File tmpFile = null;
        Boolean isModel = jsonObject.getBoolean("isModel");

        if(isModel){
            Workbook wb = generateWorkBook();

            tmpFile = ExcelUtil.writeXlsFile(wb, "商铺导入模板", ".xlsx");
        } else {
            PageCondition query = Condition.createPage(false);
            JSONArray employeeNos = jsonObject.getJSONArray("employeeNos");
            if(Objects.nonEmpty(employeeNos)){
                query.markBegin();
                for (Object item: employeeNos) {
                    query.like("b.employeeNos",String.valueOf(item)).or();
                }
                query.markEnd().and();
            }

            String search = jsonObject.getString("search");
            if(Objects.nonEmpty(search)){
                query.markBegin();
                query.like("s.viewName", search).or();
                query.like("s.name", search).or();

                query.markEnd();
            }


            String communityName = jsonObject.getString("communityName");
            if(Objects.nonEmpty(communityName)){
                query.like("s.communityName", communityName);
            }

            String shopClassifyNo = jsonObject.getString("shopClassifyNo");
            if(Objects.nonEmpty(shopClassifyNo)){
                query.eq("s.shopClassifyNo", shopClassifyNo);
            }

            String shopClassifyName = jsonObject.getString("shopClassifyName");
            if(Objects.nonEmpty(shopClassifyName)){
                query.like("s.shopClassifyName", shopClassifyName);
            }

            String unitName = jsonObject.getString("unitName");
            if(Objects.nonEmpty(unitName)){
                query.like("s.unitName", unitName);
            }

            String name = jsonObject.getString("name");
            if(Objects.nonEmpty(name)){
                query.like("s.name", name);
            }

            String communityNo = jsonObject.getString("communityNo");
            if(Objects.nonEmpty(communityNo)){
                query.eq("s.communityNo", communityNo);
            }

            String ownerName = jsonObject.getString("ownerName");
            if(Objects.nonEmpty(ownerName)){
                query.like("s.ownerName", ownerName);
            }

            String ownerMobile = jsonObject.getString("ownerMobile");
            if(Objects.nonEmpty(ownerMobile)){
                query.like("s.ownerMobile", ownerMobile);
            }


            query.eq("s.deleted", false);
            jsonObject.put("pageNo",1);
            jsonObject.put("pageSize",Short.MAX_VALUE);
            query.page(jsonObject);

            PermissionNameDto dto = houseService.getShopsPermissionNameDto();
            houseService.setDataSql(query, dto, jsonObject, null);
            Page<Map<String, Object>> page = shopDao.loadPage(query);

            Set<String> employeeIds = new HashSet<>();
            page.getList().forEach(item -> {
                String strs = String.valueOf(item.get("employeeNos"));
                if(Objects.nonEmpty(strs)){
                    employeeIds.addAll(Arrays.asList(strs.split(",")));
                }
            });

            Map<String, JSONObject> employeeMap = getEmployeeMap(token, new ArrayList<>(employeeIds));
            page.getList().forEach(item -> {
                List<String> employeeNames = new ArrayList<>();
                String strs = String.valueOf(item.get("employeeNos"));
                if(Objects.nonEmpty(strs)){
                    List<String> ids = Arrays.asList(strs.split(","));
                    ids.forEach(id ->{
                        JSONObject employee = employeeMap.get(id);
                        if (Objects.nonNull(employee)) {
                            employeeNames.add(employee.getString("name"));
                        }
                    });
                }
                item.put("employeeNames", employeeNames);
            });
            List<Map<String, Object>> shopListMap=page.getList();
            Workbook wb = generateWorkBook(shopListMap);

            tmpFile = ExcelUtil.writeXlsFile(wb, "商铺信息", ".xlsx");
        }
        return Result.download(tmpFile);
    }

    @ReqMapping("/checkFile")
    public Object checkFile(JSONObject jsonObject) throws Exception {
        InputStream is = fileUrlConfig.download(jsonObject.getString("fileId"));
        Workbook wb = WorkbookFactory.create(is);
        Sheet sheet = wb.getSheetAt(0);

        // 3行表头 开始读
        Row firstRow = sheet.getRow(sheet.getFirstRowNum() + 2);
        List<String> errMsgs = new ArrayList<>();

        for (int i = firstRow.getFirstCellNum(); i < firstRow.getLastCellNum(); i++) {
            firstRow.getCell(i).setCellType(CellType.STRING);
            String s = firstRow.getCell(i).getStringCellValue();
            if (i < EXCEL_IMPORT_HEADER.length) {
                if (!EXCEL_IMPORT_HEADER[i].equals(s)) {
                    errMsgs.add("请确认【" + EXCEL_IMPORT_HEADER[i] + "】为第" + (i + 1) + "列");
                }
            }
        }

        JSONObject errorJson = new JSONObject();
        // 表头校验结果
        if (!errMsgs.isEmpty()) {
            errorJson.put("normalCount", 0);
            errorJson.put("errCount", 0);
            errorJson.put("successCount", 0);
            errorJson.put("errMsgs", errMsgs);
            return Result.error(0, "数据解析异常", errorJson);
        }

        Map<Integer,Integer> errCount = new HashMap<>();
        Integer size = 0;

        // 第4行开始遍历获取数据
        for (int rIndex = sheet.getFirstRowNum() + 3; rIndex <= sheet.getLastRowNum(); rIndex++) {
            Row row = sheet.getRow(rIndex);

            if(Objects.isNull(row)){
                continue;
            }

            // 校验数据
            checkExcelData(row, (rIndex + 1), errMsgs, errCount);

            size++;
        }

        errorJson.put("normalCount", size);
        if(size > 3000){
            errMsgs = new ArrayList<>();
            errMsgs.add("最多支持导入3000条数据");
            errorJson.put("errCount", 0);
            errorJson.put("successCount", 0);
            errorJson.put("errMsgs", errMsgs);
            return Result.error(0, "数据解析异常", errorJson);
        }

        // 数据读取结果
        if (!errMsgs.isEmpty()) {
            int errSum = 0;
            for (int val: errCount.keySet()) {
                errSum++;
            }

            errorJson.put("errMsgs", errMsgs);
            errorJson.put("errCount", errSum);
            errorJson.put("successCount", size - errSum);

            return Result.error(0, "数据解析异常", errorJson);
        }

        errorJson.put("errMsgs", errMsgs);
        errorJson.put("errCount", 0);
        errorJson.put("successCount", size);
        return Result.success("成功", errorJson);
    }

    @ReqMapping("/readFile")
    public Object readFile(Token token, JSONObject jsonObject) throws Exception {
        InputStream is = fileUrlConfig.download(jsonObject.getString("fileId"));
        Workbook wb = WorkbookFactory.create(is);
        Sheet sheet = wb.getSheetAt(0);

        List<JSONObject> houseJsons = new ArrayList<>();
        // 第4行开始遍历获取数据
        for (int rIndex = sheet.getFirstRowNum() + 3; rIndex <= sheet.getLastRowNum(); rIndex++) {
            Row row = sheet.getRow(rIndex);

            if(Objects.isNull(row)){
                continue;
            }

            JSONObject json = new JSONObject();
            // 写入数据
            checkExcelData(row, json);

            houseJsons.add(json);
        }
        List<String> childDepartments = getChildDepartments(token.getDepartments());
        JSONArray ownerJsons = new JSONArray();
        for (JSONObject json : houseJsons) {
            String shopClassifyName = json.getString("shopClassifyName");
            //房屋是否已经存在
            FindOne<Shop> find = jdbcSession.findOne(Shop.class)
                    .eq("deleted", false)
                    .eq("communityName", json.getString("communityName"))
                    .eq("shopClassifyName", shopClassifyName)
                    .eq("name", json.getString("name"));
            Shop shop = find.exe(false);

            //新增修改业主信息
            if (Objects.nonNull(shop)) {
                setExcelData(shop, json);
                jdbcSession.updateById(shop);

                basicService.saveOperateRecord(token, shop.getId(), businessType, "2", "上传文档修改");
            } else {
                shop = Pool.newInstance(Shop.class);
                setExcelData(shop, json);

                shop.setCreate_by(token.getUsername());
                shop.setCreateUserId(token.getUuid());
                shop.setCreateDepartment(token.getDepartments());
                shop.setCreateChildDepartment(childDepartments);

                jdbcSession.insert(shop);

                basicService.saveOperateRecord(token, shop.getId(), businessType, "1", "上传文档新增");
            }

            if (Objects.nonEmpty(json.getString("mobile"))) {
                JSONObject ownerJson = new JSONObject();
                ownerJson.put("houseNo", shop.getId());
                ownerJson.put("realname", json.getString("realname"));
                ownerJson.put("mobile", json.getString("mobile"));
                ownerJson.put("cardType", CardType.ID_CARD.getId());
                ownerJson.put("cardNo", json.getString("cardNo"));
                ownerJson.put("houseType", HouseType.SHOP.getId());
                ownerJsons.add(ownerJson);
            }
        }

        //批量写入业主信息
        if (Objects.nonEmpty(ownerJsons)) {
            //批量新增员工跟进的住户信息
            doveClient.post("/crm/resident/service/batchSaveOrUpdateOwner", (http) -> {
                JSONObject body = new JSONObject();
                body.put("ownerList", ownerJsons);
                http.setBody(body.toJSONString());
            });
        }

        return Result.success();
    }

    private void setExcelData(Shop shop, JSONObject json) throws Exception {
        shop.setCommunityNo(json.getString("communityNo"));
        shop.setCommunityName(json.getString("communityName"));
        shop.setShopClassifyNo(json.getString("shopClassifyNo"));
        shop.setShopClassifyName(json.getString("shopClassifyName"));
        shop.setName(json.getString("name"));
        shop.setPropertyType(PropertyType.get(json.getString("propertyType")));
        shop.setUseArea(json.getBigDecimal("useArea"));
        shop.setBuildArea(json.getBigDecimal("buildArea"));
        shop.setPayArea(json.getBigDecimal("payArea"));
        shop.setViewName(json.getString("viewName"));
        shop.setSalesStatus(SalesStatus.get(json.getString("salesStatus")));
        shop.setHarvestStatus(HarvestStatus.get(json.getString("harvestStatus")));
        shop.setDecoratedStasus(DecoratedStasus.get(json.getString("decoratedStasus")));
        shop.setRentStasus(RentStasus.get(json.getString("rentStasus")));

        Community com = Pool.get(Community.class, shop.getCommunityNo());
        shop.setDepartmentNo(com.getParent_id());
        shop.setDepartmentNos(com.getParent_ids());

        // 更新标签信息
        List<String> tags = this.saveOrUpdateTag(shop);
        if(Objects.nonEmpty(tags)){
            shop.setTags(tags);
        }
    }

    private void checkExcelData(Row row, int index, List<String> errMsgs, Map<Integer,Integer> errCount) {

        String communityName = ExcelUtil.getCellValue(row.getCell(0));
        Community community = null;
        if (Objects.isEmpty(communityName)) {
            errCount.put(index, 1);
            errMsgs.add("第" + index + "行：【项目/小区】不能为空");
        } else {
            community = jdbcSession.findOne(Community.class)
                    .eq("deleted", false)
                    .eq("name", communityName)
                    .exe();
            if (Objects.isNull(community)) {
                errCount.put(index, 1);
                errMsgs.add("第" + index + "行,未获取到当前【小区信息】,请检查");
            }
        }

        String shopClassifyName = ExcelUtil.getCellValue(row.getCell(1));
        if (Objects.isEmpty(shopClassifyName)) {
            errCount.put(index, 1);
            errMsgs.add("第" + index + "行：【商铺分类】不能为空");
        } else {
            if (Objects.nonNull(community)) {
                FindOne<ShopClassify> shopClassifyFindOne = jdbcSession.findOne(ShopClassify.class)
                        .eq("deleted", false)
                        .eq("communityNo", community.getId())
                        .eq("name", shopClassifyName);


                ShopClassify shopClassify = shopClassifyFindOne.exe();
                if (Objects.isNull(shopClassify)) {
                    errCount.put(index, 1);
                    errMsgs.add("第" + index + "行,当前小区下未获取到【商铺分类信息】,请检查");
                }
            }
        }

        String shopName = ExcelUtil.getCellValue(row.getCell(2));
        if (Objects.isEmpty(shopName)) {
            errCount.put(index, 1);
            errMsgs.add("第" + index + "行：【商铺】不能为空");
        }

        String propertyType = ExcelUtil.getCellValue(row.getCell(4));
        if (Objects.nonEmpty(propertyType) && Objects.isNull(PropertyType.get(propertyType))) {
            errCount.put(index, 1);
            errMsgs.add("第" + index + "行：输入的【物业类型】不匹配");
        }

        try {
            ExcelUtil.getBigDecimalFromCell(row, 5);
        } catch (Exception e) {
            errCount.put(index, 1);
            errMsgs.add("第" + index + "行：【建筑面积】校验出现异常请检查");
        }

        try {
            ExcelUtil.getBigDecimalFromCell(row, 6);
        } catch (Exception e) {
            errCount.put(index, 1);
            errMsgs.add("第" + index + "行：【计费面积】校验出现异常请检查");
        }

        try {
            BigDecimal payArea = ExcelUtil.getBigDecimalFromCell(row, 7);
            if(Objects.isNull(payArea)){
                errCount.put(index, 1);
                errMsgs.add("第" + index + "行：【计费面积】不能为空");
            }
        } catch (Exception e) {
            errCount.put(index, 1);
            errMsgs.add("第" + index + "行：【计费面积】校验出现异常请检查");
        }

        String salesStatus = ExcelUtil.getCellValue(row.getCell(8));
        if (Objects.nonEmpty(salesStatus) && Objects.isNull(SalesStatus.get(salesStatus))) {
            errCount.put(index, 1);
            errMsgs.add("第" + index + "行：输入的【销售状态】不匹配");
        }

        String harvestStatus = ExcelUtil.getCellValue(row.getCell(9));
        if (Objects.nonEmpty(harvestStatus) && Objects.isNull(HarvestStatus.get(harvestStatus))) {
            errCount.put(index, 1);
            errMsgs.add("第" + index + "行：输入的【收房状态】不匹配");
        }

        String decoratedStasus = ExcelUtil.getCellValue(row.getCell(10));
        if (Objects.nonEmpty(decoratedStasus) && Objects.isNull(DecoratedStasus.get(decoratedStasus))) {
            errCount.put(index, 1);
            errMsgs.add("第" + index + "行：输入的【装修状态】不匹配");
        }

        String rentStasus = ExcelUtil.getCellValue(row.getCell(11));
        if (Objects.nonEmpty(rentStasus) && Objects.isNull(RentStasus.get(rentStasus))) {
            errCount.put(index, 1);
            errMsgs.add("第" + index + "行：输入的【出租状态】不匹配");
        }

        String realname = ExcelUtil.getCellValue(row.getCell(12));


        String mobile = ExcelUtil.getCellValue(row.getCell(13));

        if (isMixture(realname, mobile)) {
            errCount.put(index, 1);
            errMsgs.add("第" + index + "行：【姓名和手机号码一旦填写一项必填项需填满才能导入】");
        }

    }

    private void checkExcelData(Row row, JSONObject json) {

        String communityName = ExcelUtil.getCellValue(row.getCell(0));
        Community community = null;
        if (Objects.nonEmpty(communityName)) {
            community = jdbcSession.findOne(Community.class)
                    .eq("deleted", false)
                    .eq("name", communityName)
                    .exe();
            if (Objects.nonNull(community)) {
                json.put("communityNo", community.getId());
                json.put("communityName", communityName);
            }
        }

        String shopClassifyName = ExcelUtil.getCellValue(row.getCell(1));
        if (Objects.nonEmpty(shopClassifyName)) {
            if (Objects.nonNull(community)) {
                FindOne<ShopClassify> shopClassifyFind = jdbcSession.findOne(ShopClassify.class)
                        .eq("deleted", false)
                        .eq("communityNo", community.getId())
                        .eq("name", shopClassifyName);
                ShopClassify shopClassify = shopClassifyFind.exe(false);
                if (Objects.nonNull(shopClassify)) {
                    json.put("shopClassifyNo", shopClassify.getId());
                    json.put("shopClassifyName",shopClassify.getName());
                }
            }
        }

        String shopName = ExcelUtil.getCellValue(row.getCell(2));
        if (Objects.nonEmpty(shopName)) {
            json.put("name",shopName);
        }

        json.put("viewName", ExcelUtil.getCellValue(row.getCell(3)));
        json.put("propertyType", ExcelUtil.getCellValue(row.getCell(4)));

        BigDecimal buildArea = ExcelUtil.getBigDecimalFromCell(row, 5);
        json.put("buildArea", buildArea);

        BigDecimal useArea = ExcelUtil.getBigDecimalFromCell(row, 6);
        json.put("useArea", useArea);

        BigDecimal payArea = ExcelUtil.getBigDecimalFromCell(row, 7);
        json.put("payArea", payArea);

        json.put("salesStatus", ExcelUtil.getCellValue(row.getCell(8)));
        json.put("harvestStatus", ExcelUtil.getCellValue(row.getCell(9)));
        json.put("decoratedStasus", ExcelUtil.getCellValue(row.getCell(10)));
        json.put("rentStasus", ExcelUtil.getCellValue(row.getCell(11)));
        json.put("realname", ExcelUtil.getCellValue(row.getCell(12)));
        json.put("mobile", ExcelUtil.getCellValue(row.getCell(13)));
        json.put("cardNo", ExcelUtil.getCellValue(row.getCell(14)));
    }

    private Sheet setSheetCellStyle(XSSFWorkbook wb) {
        //设置字体颜色+文字水平居中
        CellStyle fontColorCellStyle = wb.createCellStyle();
        XSSFFont font = wb.createFont();
        XSSFColor color = new XSSFColor(new java.awt.Color(255, 0, 0));
        font.setColor(color);
        fontColorCellStyle.setAlignment(HorizontalAlignment.CENTER);
        fontColorCellStyle.setFont(font);

        // 允许文字换行
        XSSFFont fontStyle = wb.createFont(); // 字体样式
//        fontStyle.setBold(true);// 加粗
        fontStyle.setFontName("宋体");
        fontStyle.setFontHeightInPoints((short) 16); // 大小
        CellStyle noticeCellStyle = wb.createCellStyle();
        noticeCellStyle.setWrapText(true);
        noticeCellStyle.setFont(fontStyle);

        // 文字水平居中
        CellStyle fontCellStyle = wb.createCellStyle();
        fontCellStyle.setAlignment(HorizontalAlignment.CENTER);

        Sheet sheet = wb.createSheet();
        // 设置第1行 合并16格
        sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 14));
        // 设置第2行 合并格
        sheet.addMergedRegion(new CellRangeAddress(1, 1, 0, 7));
        sheet.addMergedRegion(new CellRangeAddress(1, 1, 8, 11));
        sheet.addMergedRegion(new CellRangeAddress(1, 1, 12, 14));

        //第1行 须知内容
        Row noticeRow = sheet.createRow(0);
        Cell noticeRowCell = noticeRow.createCell(0);
        noticeRowCell.setCellStyle(noticeCellStyle);
        StringBuffer notice = new StringBuffer();
        notice.append("填写须知：").append("\n")
                .append(" <1>不能在本excel表中对项目、商铺分类信息、进行增加、删除、修改，若项目、商铺分类不足，请进入“企业管理后台-应用管理-资产管理”进行添加，完成后重新下载新模板；").append("\n")
                .append(" <2>红色字段为必填字段，黑色字段为选填字段；").append("\n")
                .append(" <3>商铺信息为必填项，业主信息可不填，业主信息一旦填写一项必填项需填满才能导入；").append("\n")
                .append(" <4>商铺分类：请先到商铺管理-商铺分类先添加好或先通过excel导入好，再到本excel里填入；").append("\n");

        noticeRowCell.setCellValue(notice.toString());
        //自动设置行高
        int colLength = noticeRowCell.getStringCellValue().getBytes().length * 6;
        noticeRow.setHeight((short) (colLength));

        //第2行 员工信息：
        Row firstRow = sheet.createRow(1);
        Cell firstRowCell = firstRow.createCell(0);
        firstRowCell.setCellValue("商铺信息");
        firstRowCell.setCellStyle(fontCellStyle);
        firstRowCell = firstRow.createCell(8);
        firstRowCell.setCellValue("商铺状态");
        firstRowCell.setCellStyle(fontCellStyle);
        firstRowCell = firstRow.createCell(12);
        firstRowCell.setCellValue("业主信息");
        firstRowCell.setCellStyle(fontCellStyle);

        //第3行 表头
        Row headerRow = sheet.createRow(2);
        for (int i = 0; i < EXCEL_IMPORT_HEADER.length; i++) {
            Cell cell = headerRow.createCell(i);
            if (i <= 2 || i == 7 || i == 12 || i ==13) {
                cell.setCellStyle(fontColorCellStyle);
            } else {
                cell.setCellStyle(fontCellStyle);
            }
            cell.setCellValue(EXCEL_IMPORT_HEADER[i]);
        }

        return sheet;
    }

    public XSSFWorkbook generateWorkBook() throws Exception {
        // 生成模板文件
        XSSFWorkbook wb = new XSSFWorkbook();

        // 设置头信息
        Sheet sheet = setSheetCellStyle(wb);

        int cellNum = 0;

        Row row = sheet.createRow(3);
        row.createCell(cellNum++).setCellValue("七星商业广场");
        row.createCell(cellNum++).setCellValue("负一层商铺");
        row.createCell(cellNum++).setCellValue("S101(示例)");
        row.createCell(cellNum++).setCellValue("S101");
        row.createCell(cellNum++).setCellValue("商铺");
        row.createCell(cellNum++).setCellValue("58");
        row.createCell(cellNum++).setCellValue("58");
        row.createCell(cellNum++).setCellValue("50");
        row.createCell(cellNum++).setCellValue("未售");
        row.createCell(cellNum++).setCellValue("未收房");
        row.createCell(cellNum++).setCellValue("未装修");
        row.createCell(cellNum++).setCellValue("未出租");
        row.createCell(cellNum++).setCellValue("张小明");
        row.createCell(cellNum++).setCellValue("18888888888");
        row.createCell(cellNum++).setCellValue("身份证");
        row.createCell(cellNum++).setCellValue("430535198012080000");


        // 自动列宽
        for (int i = 0; i < cellNum; i++) {
            ExcelUtil.autoSizeColumn(sheet, i);
        }
        return wb;
    }

    public XSSFWorkbook generateWorkBook(List<Map<String,Object>> list) throws Exception {
        Shop shop = Pool.newInstance(Shop.class);
        // 生成模板文件
        XSSFWorkbook wb = new XSSFWorkbook();

        // 设置头信息
        Sheet sheet = setSheetCellStyle(wb);

        Set<String> ownerNos = new HashSet<>();
        for (int i = 0; i < list.size(); i++) {
            Map<String, Object> shopMap = list.get(i);
            Beans.from(shopMap).to(shop).copy();
            setProperty(shop,shopMap);
            if (Objects.nonEmpty(shop.getOwnerNo())) {
                ownerNos.add(shop.getOwnerNo());
            }
        }

        Map<String, JSONObject> residentMap = getResidentMap(new ArrayList<>(ownerNos));

        int cellNum = 0;
        for (int i = 0; i < list.size(); i++) {
            cellNum = 0;
            Map<String, Object> shopMap= list.get(i);
            Beans.from(shopMap).to(shop).copy();
            setProperty(shop,shopMap);
            Row row = sheet.createRow(i + 3);
            row.createCell(cellNum++).setCellValue(shop.getCommunityName());
            row.createCell(cellNum++).setCellValue(shop.getShopClassifyName());
            row.createCell(cellNum++).setCellValue(shop.getName());
            row.createCell(cellNum++).setCellValue(shop.getViewName());
            row.createCell(cellNum++).setCellValue(Objects.nonNull(shop.getPropertyType()) ? shop.getPropertyType().getDesc() : "");
            row.createCell(cellNum++).setCellValue(Objects.nonNull(shop.getBuildArea()) ? shop.getBuildArea().setScale(0) + "" : "");
            row.createCell(cellNum++).setCellValue(Objects.nonNull(shop.getUseArea()) ? shop.getUseArea().setScale(0) + "" : "");
            row.createCell(cellNum++).setCellValue(shop.getPayArea().setScale(0) + "");
            row.createCell(cellNum++).setCellValue(Objects.nonNull(shop.getSalesStatus()) ? shop.getSalesStatus().getDesc() : "");
            row.createCell(cellNum++).setCellValue(Objects.nonNull(shop.getHarvestStatus()) ? shop.getHarvestStatus().getDesc() : "");
            row.createCell(cellNum++).setCellValue(Objects.nonNull(shop.getDecoratedStasus()) ? shop.getDecoratedStasus().getDesc() : "");
            row.createCell(cellNum++).setCellValue(Objects.nonNull(shop.getRentStasus()) ? shop.getRentStasus().getDesc() : "");

            JSONObject resident = residentMap.get(shop.getOwnerNo());
            if (Objects.nonEmpty(resident)) {
                row.createCell(cellNum++).setCellValue(resident.getString("realname"));
                row.createCell(cellNum++).setCellValue(resident.getString("mobile"));
                row.createCell(cellNum++).setCellValue(resident.getString("cardNo"));
            }
        }

        // 自动列宽
        for (int i = 0; i < cellNum; i++) {
            ExcelUtil.autoSizeColumn(sheet, i);
        }
        return wb;
    }

    public Map<String, JSONObject> getResidentMap(List<String> ids) throws Exception {
        if (Objects.nonEmpty(ids)) {
            JSONObject result = doveClient.post("/crm/resident/service/getResidentList", http -> {
                JSONObject body = new JSONObject();
                body.put("ids", ids);

                http.setBody(body.toString());
            });

            JSONArray data = result.getJSONObject("data").getJSONArray("list");

            if (Objects.isNull(result) || Objects.isNull(data)) {
                return new HashMap<>();
            }

            Map<String, JSONObject> residentMap = new HashMap<>();
            data.forEach(item -> {
                JSONObject obj = (JSONObject) item;
                residentMap.put(((JSONObject) item).getString("id"), obj);
            });

            return residentMap;
        } else {
            return new HashMap<>();
        }
    }

    public List<String> getChildDepartments(List<String> departments) throws Exception {
        JSONObject result = doveClient.post("/basic/department/service/getChildDepartments", http->{
            JSONObject body = new JSONObject();
            body.put("pidList", departments);
            http.setBody(body.toString());
        });

        if (result.getIntValue("code") == 200) {
            JSONArray data = result.getJSONArray("data");
            if(Objects.nonEmpty(data)){
                return JSONObject.parseArray(data.toJSONString(), String.class);
            }
        }
        return new ArrayList<>();
    }

    private PermissionNameDto getShopClassifyPermissionNameDto(){
        PermissionNameDto dto = new PermissionNameDto();
        // 指定人员
        dto.setManageUserId("employeeNos");
        // 创建人的部门
        dto.setDepartmentNo("createDepartment");
        // 创建人的部门树
        dto.setDepartmentNos("createChildDepartment");
        // 指定部门
        dto.setManageDepartmentNo("departmentNo");

        return dto;
    }

    /**
     * 全部不为空
     *
     * @param strs
     * @return
     */
    public static boolean isAllNotEmpty(String... strs) {
        if (Objects.isEmpty(strs)) {
            return false;
        }
        for (String str : strs) {
            if (Objects.isEmpty(str)) {
                return false;
            }
        }
        return true;
    }

    /**
     * 全部为空
     *
     * @param strs
     * @return
     */
    public static boolean isAllEmpty(String... strs) {
        if (Objects.isEmpty(strs)) {
            return true;
        }
        for (String str : strs) {
            if (Objects.nonEmpty(str)) {
                return false;
            }
        }
        return true;
    }

    /**
     * 不全为空，也不全为非空
     *
     * @param strs
     * @return
     */
    public static boolean isMixture(String... strs) {
        return !isAllEmpty(strs) && !isAllNotEmpty(strs);
    }
}
